package com.shadowlight.hero_story.cmdHandler;

import com.shadowlight.hero_story.login.LoginService;
import com.shadowlight.hero_story.msg.GameMsgProtocol;
import com.shadowlight.hero_story.pojo.User;
import com.shadowlight.hero_story.pojo.UserRepository;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;

/**
 * @Description 用户登陆的处理器
 * @Author cz
 * @Date 2022/3/2
 */
@Slf4j
public class UserLoginCmdHandler implements ICmdHandler<GameMsgProtocol.UserLoginCmd> {

    @Override
    public void handle(ChannelHandlerContext channelHandlerContext, GameMsgProtocol.UserLoginCmd msg) {
        String userName = msg.getUserName();
        String password = msg.getPassword();
        log.debug("账号:{} 密码:{} 的用户登陆了", userName, password);

        try {
            LoginService.getInstance().userLogin(userName, password, userEntity -> {
                if (userEntity == null) {
                    log.error("用户登陆失败: userName:{}, password:{}", userName, password);
                    return;
                }

                int id = userEntity.getId();

                //存储登陆用户信息
                //默认初始血量为100
                UserRepository.getInstance().save(new User(id, userName, userEntity.getHeroAvatar(), 100, null, false));

                GameMsgProtocol.UserLoginResult.Builder loginResultBuilder = GameMsgProtocol.UserLoginResult.newBuilder();
                loginResultBuilder.setUserId(id);
                loginResultBuilder.setUserName(userName);
                //这里不设置英雄，让用户可以自己选择，设置的话会跳过选择英雄界面

                //为客户端信道绑定一个用户ID
                channelHandlerContext.channel().attr(AttributeKey.valueOf("userId")).set(id);
                GameMsgProtocol.UserLoginResult loginResult = loginResultBuilder.build();
                channelHandlerContext.channel().writeAndFlush(loginResult);
            });
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}
